#!/bin/bash

source /home/shell/util.sh

# 安装函数
function install () {

cat<<EOF
安装须知：
1、需预先安装MySQL Master库
2、需预先安装MySQL Slave库
3、需完成主从配置
4、需创建好数据库
5、默认实现读写分离配置
EOF
  puase
  requireJava

  printInfo "proxy版本列表"
  curl -sL https://mirrors.tuna.tsinghua.edu.cn/apache/shardingsphere/|grep -Po "<a href=\"\d+.*\/\""|perl -pe "s/<a href=\"(.*)\/\"/\1/g"
  while [ true ]; do
      read -p "请选择版本[仅支持5.0以上]：" version
      if [[ -z "${version}" ]]; then
          printFail "请重新输入版本！"
          continue;
      else
          break;
      fi
  done
  download /opt/shardingsphere-proxy.tar.gz https://mirrors.tuna.tsinghua.edu.cn/apache/shardingsphere/${version}/apache-shardingsphere-${version}-shardingsphere-proxy-bin.tar.gz
  tar -xf /opt/shardingsphere-proxy.tar.gz -C /opt
  rm -rf /opt/shardingsphere-proxy.tar.gz
  mv /opt/apache-shardingsphere-* /opt/shardingsphere-proxy
  mkdir -p /opt/shardingsphere-proxy/ext-lib
  download /opt/shardingsphere-proxy/ext-lib/mysql-connector-java-8.0.24.jar https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.24/mysql-connector-java-8.0.24.jar
}

function install-ui () {
  printInfo "proxy-ui版本列表"
  curl -sL  https://mirrors.tuna.tsinghua.edu.cn/apache/shardingsphere/|grep -Po "shardingsphere-ui-\d+.*?(?=\/)"|uniq|perl -pe "s/shardingsphere-ui-(.*)/\1/g"
  while [ true ]; do
        read -p "请选择UI版本[仅支持5.0以上]：" ui_version
        if [[ -z "${ui_version}" ]]; then
            printFail "请重新输入版本！"
            continue;
        else
            break;
        fi
    done
  download /opt/shardingsphere-ui.tar.gz https://mirrors.tuna.tsinghua.edu.cn/apache/shardingsphere/shardingsphere-ui-${ui_version}/apache-shardingsphere-${ui_version}-shardingsphere-ui-bin.tar.gz
  tar -xf /opt/shardingsphere-ui.tar.gz -C /opt
  rm -rf /opt/shardingsphere-ui.tar.gz
  mv /opt/apache-shardingsphere-*-ui-bin/ /opt/shardingsphere-ui
}

function ui-config () {
  read -p "ui web端口[8088]：" ui_http_port
  ui_http_port=${ui_http_port:-"8088"}

  read -p "管理员用户名[admin]：" user_admin_username
  user_admin_username=${user_admin_username:-"admin"}

  read -p "管理员${user_admin_username}的密码[admin]：" user_admin_password
  user_admin_password=${user_admin_password:-"admin"}

  sed -ri "s/server.port=8088/server.port="${ui_http_port}"/g" /opt/shardingsphere-ui/conf/application.properties
  sed -ri "s/user.admin.username=admin/user.admin.username="${user_admin_username}"/g" /opt/shardingsphere-ui/conf/application.properties
  sed -ri "s/user.admin.password=admin/user.admin.password="${user_admin_password}"/g" /opt/shardingsphere-ui/conf/application.properties

  sed -ri "s@nohup java@nohup /opt/jdk/bin/java@g" /opt/shardingsphere-ui/bin/start.sh

  firewall-addport ${ui_http_port}
}

function ui-run () {
bash /home/shell/serviced-install.sh<<EOF
2


shardingsphere-ui
/opt/shardingsphere-ui/bin/start.sh




EOF
printInfo "==================================sharding-proxy====sharding-ui=================================="
printInfo "proxy地址：${host_addr}"
printInfo "proxy端口：${proxy_port}"
printInfo "proxy用户：${proxy_db_username}"
printInfo "proxy用户${proxy_db_username}的密码：${proxy_db_passwd}"
printInfo "proxy数据库：${db_name}"
printInfo "proxy-ui地址：http://${host_addr}:${ui_http_port}/"
printInfo "proxy-ui用户名：${user_admin_username}"
printInfo "proxy-ui用户${user_admin_username}的密码：${user_admin_password}"
printInfo "==================================sharding-proxy====sharding-ui=================================="
}



# 配置函数
function config () {

  read -p "数据库名称：" db_name

  read -p "数据库user[dev_user]：" db_username
  db_username=${db_username:-"dev_user"}

  read -p "数据库用户${db_username}的密码[123456]：" db_passwd
  db_passwd=${db_passwd:-"123456"}

  read -p "Proxy数据库user[dev_user]：" proxy_db_username
  proxy_db_username=${proxy_db_username:-"dev_user"}

  read -p "Proxy数据库用户${proxy_db_username}的密码[123456]：" proxy_db_passwd
  proxy_db_passwd=${proxy_db_passwd:-"123456"}

  read -p "master主机：" db_master_host

  read -p "slave主机：" db_slave_host

  read -p "proxy端口[3307]：" proxy_port
  proxy_port=${proxy_port:-"3307"}

  read -p "是否安装zookeeper？[y/n]" install_zookeeper
  case "${install_zookeeper}" in
    y|Y)
      bash /home/shell/zookeeper-install.sh
    ;;
    *)
      read -p "zookeeper地址[127.0.0.1]" zookeeper_addr
      zookeeper_addr=${zookeeper_addr:-"127.0.0.1"}

      read -p "zookeeper端口[2181]" zookeeper_port
      zookeeper_port=${zookeeper_port:-"2181"}
    ;;
  esac

  if [ ! -f "/opt/shardingsphere-proxy/conf/server.yaml.bak" ]; then
      cp /opt/shardingsphere-proxy/conf/server.yaml /opt/shardingsphere-proxy/conf/server.yaml.bak
  fi

  sed -ri "s@nohup java@nohup /opt/jdk/bin/java@g" /opt/shardingsphere-proxy/bin/start.sh

  firewall-addport ${proxy_port}

tee /opt/shardingsphere-proxy/conf/config-my.yaml<<EOF
schemaName: ${db_name}

dataSources:
 write_ds:
   url: jdbc:mysql://${db_master_host}:3306/${db_name}?useUnicode=true&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
   username: ${db_username}
   password: ${db_passwd}
   connectionTimeoutMilliseconds: 30000
   idleTimeoutMilliseconds: 60000
   maxLifetimeMilliseconds: 1800000
   maxPoolSize: 50
   minPoolSize: 1
 read_ds_0:
   url: jdbc:mysql://${db_slave_host}:3306/${db_name}?useUnicode=true&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
   username: ${db_username}
   password: ${db_passwd}
   connectionTimeoutMilliseconds: 30000
   idleTimeoutMilliseconds: 60000
   maxLifetimeMilliseconds: 1800000
   maxPoolSize: 50
   minPoolSize: 1

rules:
- !READWRITE_SPLITTING
 dataSources:
   pr_ds:
     writeDataSourceName: write_ds
     readDataSourceNames:
       - read_ds_0
EOF

tee /opt/shardingsphere-proxy/conf/server.yaml<<EOF
mode:
 type: Cluster
 repository:
   type: ZooKeeper
   props:
     namespace: governance_ds
     server-lists: ${zookeeper_addr}:${zookeeper_port}
     retryIntervalMilliseconds: 500
     timeToLiveSeconds: 60
     maxRetries: 3
     operationTimeoutMilliseconds: 500
 overwrite: false

rules:
 - !AUTHORITY
   users:
     - ${proxy_db_username}@:${proxy_db_passwd}
   provider:
     type: ALL_PRIVILEGES_PERMITTED
 - !TRANSACTION
   defaultType: XA
   providerType: Atomikos

props:
  max-connections-size-per-query: 1
  kernel-executor-size: 16  # Infinite by default.
  proxy-frontend-flush-threshold: 128  # The default value is 128.
  proxy-opentracing-enabled: false
  proxy-hint-enabled: false
  sql-show: true
  check-table-metadata-enabled: false
  show-process-list-enabled: false
    # Proxy backend query fetch size. A larger value may increase the memory usage of ShardingSphere Proxy.
    # The default value is -1, which means set the minimum value for different JDBC drivers.
  proxy-backend-query-fetch-size: -1
  check-duplicate-table-enabled: false
  sql-comment-parse-enabled: false
  proxy-frontend-executor-size: 0 # Proxy frontend executor size. The default value is 0, which means let Netty decide.
    # Available options of proxy backend executor suitable: OLAP(default), OLTP. The OLTP option may reduce time cost of writing packets to client, but it may increase the latency of SQL execution
    # if client connections are more than proxy-frontend-netty-executor-size, especially executing slow SQL.
  proxy-backend-executor-suitable: OLAP
  proxy-frontend-max-connections: 0 # Less than or equal to 0 means no limitation.
  sql-federation-enabled: false
EOF

}

function addSharding () {

tee /opt/shardingsphere-proxy/conf/config-my -a<<EOF
- !SHARDING
 tables:
   # 配置表规则
   mall_order:
     # 由数据源名 + 表名组成，以小数点分隔
     actualDataNodes: pr_ds.mall_order_${202109..202110}
     # 配置分表策略
     tableStrategy:
       standard:
         # 分片列名称
         shardingColumn: create_time
         # 分片算法名称
         shardingAlgorithmName: mall_order_interval
     # 自增列生成器
     keyGenerateStrategy:
       column: order_id
       keyGeneratorName: snowflake
 # 绑定表规则列表
 bindingTables:
   - mall_order

 # 分片算法名称和配置
 shardingAlgorithms:
   # 分片算法名称
   mall_order_inline:
     # 分片算法类型
     type: INLINE
     # 分片算法属性配置
     props:
       algorithm-expression: mall_order_${order_id % 2}
   mall_order_interval:
     # 分片算法类型
     type: INTERVAL
     # 分片算法属性配置
     props:
      datetime-pattern: "yyyy-MM-dd HH:mm:ss"
      sharding-suffix-pattern: yyyyMM
      datetime-interval-unit: DAYS
      datetime-lower: "1957-12-12 00:00:00"
 
 # 分布式序列算法配置
 keyGenerators:
   # 分布式序列算法名称
   snowflake:
     # 分布式序列算法类型
     type: SNOWFLAKE
     # 分布式序列算法属性配置
     props:
       worker-id: 123
EOF
}

function run () {

bash /home/shell/serviced-install.sh<<EOF
2


shardingsphere-proxy
/opt/shardingsphere-proxy/bin/start.sh ${proxy_port}




EOF
}

# 运行安装和配置
install && config && run

install-ui && ui-config && ui-run